package com.gdue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gdue.dao.CategoryMapper;
import com.gdue.entity.Category;
import com.gdue.entity.Dish;
import com.gdue.entity.Setmeal;
import com.gdue.exception.CustomException;
import com.gdue.service.CategoryService;
import com.gdue.service.DishService;
import com.gdue.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 删除分类，删除之前先判断是否与菜品、套餐关联
     * @param id
     */
    @Override
    public void remove(Long id) {
        //查询分类与菜品是否有关联

        //构建条件吗构造器
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper=new LambdaQueryWrapper<>();
        //添加条件
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);

        int count1 = dishService.count(dishLambdaQueryWrapper);

        if (count1>0){
            //不删除，抛异常
            throw new CustomException("当前分类已关联菜品，不能删除");
        }

        //查询分类与套餐是否有关联
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper=new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        int count2 = setmealService.count(setmealLambdaQueryWrapper);
        if (count2>0){
            //不删除，抛异常
            throw new CustomException("当前分类已关联套餐，不能删除");
        }

        //正常删除分类
        super.removeById(id);
    }
}
